package com._54programer.demo.group;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com._54programer.ws.NBind;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

/**
 * @author SN
 * @date Created by on 2019/11/29
 * @description
 */
public class GroupChatServerHandler extends SimpleChannelInboundHandler<String> {

    //channel组
    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().remoteAddress() + "上线了");
        
        
        
        
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().remoteAddress() + "下线了");
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        //会遍历channelGroup中所有的channel并发送消息
        channelGroup.writeAndFlush(channel.remoteAddress() + " 加入聊天\n");
        //添加到channelGroup
        channelGroup.add(channel);
        
        NBind.bindGroup(ctx,"volt_groupId");
        
    }

    /**
     * 会自动帮我们从channelGroup组中删除
     */
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        channelGroup.writeAndFlush(channel.remoteAddress() + " 离开了\n");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        Channel channel = ctx.channel();
        //发送给除当前channel外的所有channel发送消息
        channelGroup.forEach(ch -> {
            if(channel != ch){
                ch.writeAndFlush(ch.remoteAddress() + ":" + msg + "\n");
            }
        });
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //关闭通道
        ctx.close();
    }
}
